package com.yoooya.base.third.utils.json.cp;

import com.google.gson.*;
import com.yoooya.base.third.common.WxConsts;
import com.yoooya.base.third.model.vo.cp.WxArticle;
import com.yoooya.base.third.model.vo.cp.WxCpMessage;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Type;


/**
 * 
 * @创建人 Sun Yijing
 * @创建时间 2018-07-08
 */
public class WxCpMessageGsonAdapter implements JsonSerializer<WxCpMessage> {

	public JsonElement serialize(WxCpMessage message, Type typeOfSrc,
                                 JsonSerializationContext context) {
		JsonObject messageJson = new JsonObject();
		messageJson.addProperty("agentid", message.getAgentid());
		if (StringUtils.isNotBlank(message.getTouser())) {
			messageJson.addProperty("touser", message.getTouser());
		}
		messageJson.addProperty("msgtype", message.getMsgtype());

		if (StringUtils.isNotBlank(message.getToparty())) {
			messageJson.addProperty("toparty", message.getToparty());
		}
		if (StringUtils.isNotBlank(message.getTotag())) {
			messageJson.addProperty("totag", message.getTotag());
		}
		if (WxConsts.CUSTOM_MSG_TEXT.equals(message.getMsgtype())) {
			JsonObject text = new JsonObject();
			text.addProperty("content", message.getContent());
			messageJson.add("text", text);
		}

		if (WxConsts.CUSTOM_MSG_IMAGE.equals(message.getMsgtype())) {
			JsonObject image = new JsonObject();
			image.addProperty("media_id", message.getMediaid());
			messageJson.add("image", image);
		}

		if (WxConsts.CUSTOM_MSG_FILE.equals(message.getMsgtype())) {
			JsonObject image = new JsonObject();
			image.addProperty("media_id", message.getMediaid());
			messageJson.add("file", image);
		}

		if (WxConsts.CUSTOM_MSG_VOICE.equals(message.getMsgtype())) {
			JsonObject voice = new JsonObject();
			voice.addProperty("media_id", message.getMediaid());
			messageJson.add("voice", voice);
		}

		if (WxConsts.CUSTOM_MSG_VIDEO.equals(message.getMsgtype())) {
			JsonObject video = new JsonObject();
			video.addProperty("media_id", message.getMediaid());
			video.addProperty("thumb_media_id", message.getThumbmediaid());
			video.addProperty("title", message.getTitle());
			video.addProperty("description", message.getDescription());
			messageJson.add("video", video);
		}

		if (WxConsts.CUSTOM_MSG_NEWS.equals(message.getMsgtype())) {
			JsonObject newsJsonObject = new JsonObject();
			JsonArray articleJsonArray = new JsonArray();
			for (WxArticle article : message.getArticles()) {
				JsonObject articleJson = new JsonObject();
				articleJson.addProperty("title", article.getTitle());
				articleJson
						.addProperty("description", article.getDescription());
				articleJson.addProperty("url", article.getUrl());
				articleJson.addProperty("picurl", article.getPicurl());
				articleJsonArray.add(articleJson);
			}
			newsJsonObject.add("articles", articleJsonArray);
			messageJson.add("news", newsJsonObject);
		}

		return messageJson;
	}

}
